'use strict';

const Controller = require('egg').Controller;
const { getCookieValue } = require('../public/processCookies');
const { axios } = require('../public/httpHelper');
const qs = require('qs');
const path = require('path');
const fs = require('fs');
const configDefault = require('../../config/config.default')();
/**
* @controller OltController 注释必写，swagger-doc是根据这段注释来生成接口的 ）。
*/
class OltController extends Controller {
  async testSNMP() {
    /**
        * @summary smmp测试
        * @description smmp测试
        * @router post /testSNMP
        * @request body oltsnmp value 传入参数
        */
    const options = this.ctx.request.body;
    const result = await this.ctx.service.olt.snmpTestConnect(options);
    if (result == false) {
      this.ctx.body = {
        msg: 'fail',
        status: 11,
      };
    } else {
      this.ctx.body = {
        msg: 'success',
        status: 10,
        data: result,
      };
    }
  }
  async testTelnet() {
    /**
        * @summary telnet测试
        * @description telnet测试
        * @router post /testTelnet
        * @request body olttelnet value 传入参数
        */
    const options = this.ctx.request.body;
    const result = await this.ctx.service.olt.telnetTestConnect(options);
    if (result == true) {
      this.ctx.body = {
        msg: 'success',
        status: 12,
      };
    } else {
      this.ctx.body = {
        msg: 'fail',
        status: 13,
      };
    }
  }
  async oltrefresh() {
    /**
        * @summary oltrefresh。
        * @description oltrefresh。
        * @router get /oltrefresh
        * @request query string OltId
        */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.oltrefresh(params);
    this.ctx.body = {
      msg: result.msg,
    };
  }
  async oltSingle() {
    /**
        * @summary oltSingle
        * @description oltSingle
        * @router get /oltsingle
        * @request query string OltId
        */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.oltsingle(params);
    this.ctx.body = {
      msg: '',
      status: 200,
      data: result,
    };
  }
  async refresh() {
    /**
        * @summary refresh刷新。
        * @description refresh刷新。
        * @router get /refresh
        * @request query string OltId
        */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.refresh(params);
    if (result == '') {
      this.ctx.body = {
        msg: 'refresh succrsssful',
      };
    } else {
      this.ctx.body = {
        msg: result,
      };
    }
  }
  async cardrefresh() {
    /**
        * @summary cardrefresh。
        * @description cardrefresh。
        * @router get /cardrefresh
        * @request query string OltId
        */
    const params = this.ctx.query;
    let oltResult = await this.ctx.service.common.getOltInfo(params.OltId);
    const result = await this.ctx.service.olt.cardrefresh(params,oltResult);
    global.log.desc = `${oltResult.name} ${oltResult.oltIP} card refresh`;
    this.ctx.body = {
      msg: result.msg,
    };
  }
  async ponrefresh() {
    /**
        * @summary ponportsrefresh。
        * @description ponportsrefresh。
        * @router get /ponportsrefresh
        * @request query string OltId
        */
    const params = this.ctx.query;
    let oltResult = await this.ctx.service.common.getOltInfo(params.OltId);
    const result = await this.ctx.service.olt.ponportsrefresh(params,oltResult);
    global.log.desc = `${oltResult.name} ${oltResult.oltIP} ponports refresh`;
    this.ctx.body = {
      msg: result.msg,
    };
  }
  async uplinkrefresh() {
    /**
        * @summary uplinkrefresh。
        * @description uplinkrefresh。
        * @router get /uplinkrefresh
        * @request query string OltId
        */
    const params = this.ctx.query;
    let oltResult = await this.ctx.service.common.getOltInfo(params.OltId);
    const result = await this.ctx.service.olt.uplinkrefresh(params,oltResult);
    global.log.desc = `${oltResult.name} ${oltResult.oltIP} uplink refresh`;
    this.ctx.body = {
      msg: result.msg,
    };
  }
  async vlanrefresh() {
    /**
        * @summary vlanrefresh。
        * @description vlanrefresh。
        * @router get /vlanrefresh
        * @request query string OltId
        */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.vlanrefresh(params);
    this.ctx.body = {
      msg: result.msg,
    };
  }
  async macrefresh() {
    /**
        * @summary macrefresh。
        * @description macrefresh。
        * @router get /macrefresh
        * @request query string OltId
        */
    const params = this.ctx.query;
    let oltResult = await this.ctx.service.common.getOltInfo(params.OltId);
    const result = await this.ctx.service.olt.macrefresh(oltResult);
    global.log.desc = `${oltResult.name} ${oltResult.oltIP} mac refresh`;
    this.ctx.body = {
      msg: result.msg,
    };
  }
  async listAll() {
    /**
        * @summary oltlistall
        * @description oltlistall
        * @router get /oltlistall
        */
    const { id: tid } = getCookieValue(this.ctx.cookies, 'token', 'tenant');
    const result = await this.ctx.service.olt.listAll(tid);
    this.ctx.body = {
      msg: '',
      status: 200,
      data: result,
    };
  }
  async save() {
    /**
        * @summary oltsave
        * @description oltsave
        * @router get /oltsave
        * @request query string OltId
        */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.save(params);
    this.ctx.body = {
      msg: result.msg,
    };
  }
  async backup() {
    /**
        * @summary oltbackupconfig
        * @description oltbackupconfig
        * @router get /oltbackupconfig
        * @request query string id
        */
    const params = this.ctx.query;
    console.log('我要备份了')
    const result = await this.ctx.service.olt.backup(params);
    this.ctx.body = {
      msg: result.msg,
      data: result.data,
    };
  }
  async edit() {
    /**
        * @summary editolt
        * @description editolt
        * @router post /editolt
        * @request body editolt value 传入参数
        */
    const params = this.ctx.request.body;
    const result = await this.ctx.service.olt.edit(params);
    this.ctx.body = {
      msg: result.msg,
    };
  }
  async oltInit() {
    /**
        * @summary oltinit
        * @description oltinit
        * @router get /oltinit
        * @request query string id
        */
    const params = this.ctx.query;
    const { id: tid } = getCookieValue(this.ctx.cookies, 'token', 'tenant');
    params.tid = tid;
    const result = await this.ctx.service.olt.oltInit(params);
    this.ctx.body = {
      msg: result.msg,
      status: result.flag,
    };
  }
  async upload() {
    /**
        * @summary oltuploadfile
        * @description oltuploadfile
        * @router post /oltuploadfile
        * @request body oltuploadfile value 传入参数
        */
    const file = this.ctx.request.files[0];
    const { id } = this.ctx.params;
    console.log(file, id);
    const params = {
      id,
      file,
    };
    const result = await this.ctx.service.olt.upload(params);
    this.ctx.body = {
      msg: result.msg,
    };
    // const file = fs.readFileSync(params.filepath);
    // fs.writeFileSync(path.join('./', `uploadfile/${params.filename}`), file);
    // console.log('处理上传文件', params);
    // this.ctx.body = {
    //   msg: '123',
    // };
  }
  async reboot() {
    /**
        * @summary oltreboot
        * @description oltreboot
        * @router get /oltreboot
        * @request query string OltId
        */
    const { OltId } = this.ctx.request.query;
    const result = await this.ctx.service.olt.reboot(OltId);
    this.ctx.body = {
      msg: result.msg,
    };
  }
  async active() {
    /**
        * @summary oltactive
        * @description oltactive
        * @router get /oltactive
        * @request query string OltId
        */
    const { OltId } = this.ctx.request.query;
    const result = await this.ctx.service.olt.active(OltId);
    this.ctx.body = {
      msg: result.msg,
    };
  }
  diffDate(d1, d2) {
    return (d2 - d1) / (1000 * 60 * 60 * 24);
  }
  async addOltMandate() {
    /**
        * @summary addOltMandate
        * @description addOltMandate
        * @router get /addoltmandate
        */
    const result = {
      msg: '',
      flag: true,
    };
    const { id: tid } = getCookieValue(this.ctx.cookies, 'token', 'tenant');
    const config = {
      url: `${configDefault.authorization.url}/getTenant?tenantid=${tid}`,
      method: 'get',
    };
    const response = await axios(config);
    const oltList = await this.ctx.model.Olt.find({ tid });
    if (response && response.data) {
      const tenantInfo = response.data;
      const diffDays = this.diffDate(Date.now(), tenantInfo.authorizedEndTime);
      if (diffDays < 0) {
        // TODO 更新租户，将state改为false
        const config = {
          method: 'post',
          url: `${configDefault.authorization.url}/updateTenantAuthroizeInfo`,
          data: qs.stringify({
            state: false,
            tenantid: tid,
          }),
        };
        await axios(config);
        tenantInfo.state = false;
      }
      if (!tenantInfo.state && oltList.length >= 1) {
        result.msg = `You can only add ${tenantInfo.deviceLimitNumbers} OLT`;
        result.flag = false;
      }
      if (tenantInfo.state && oltList.length >= tenantInfo.deviceLimitNumbers) {
        result.msg = `You can only add ${tenantInfo.deviceLimitNumbers} OLT`;
        result.flag = false;
      }
    } else {
      this.ctx.body = {
        msg: 'can not get tenantinfo',
        flag: false,
      };
    }
    // const result1 = await this.ctx.service.olt.addOltMandate(tid);
    this.ctx.body = {
      msg: result.msg,
      flag: result.flag,
    };
  }
  // ----------------------------------------------------------------------------------
  async list() {
    /**
        * @summary olt列表分页。
        * @description olt列表分页。
        * @router get /oltlist
        * @request query integer limit
        * @request query integer page
        */
    const params = this.ctx.query;
    const { id: tid } = getCookieValue(this.ctx.cookies, 'token', 'tenant');
    params.tid = tid;
    const result = await this.ctx.service.olt.list(params);
    this.ctx.body = {
      status: 200,
      data: result.msg,
      count: result.count,
    };
  }
  async create() {
    /**
        * @summary createolt
        * @description createolt
        * @router post /oltcreate
        * @request body oltcreate value 传入参数
        */
    const params = this.ctx.request.body;
    const { id: tid } = getCookieValue(this.ctx.cookies, 'token', 'tenant');
    params.tid = tid;
    const result = await this.ctx.service.olt.create(params);
    global.log.desc = `${params.name} ${params.oltIP} create`;
    global.log.after = `{oltType:${params.oltType},name:${params.name},IP:${params.oltIP},telnetTCPPort:${params.telnetTCPPort},oltTelnetUsername:${params.oltTelnetUsername},oltTelnetPassword:${params.oltTelnetPassword},oltManagementPassword:${params.oltManagementPassword},initCommunity:${params.initCommunity},snmpReadOnlyCommunity:${params.snmpReadOnlyCommunity},snmpReadWriteCommunity:${params.snmpReadWriteCommunity},snmpUDPPort:${params.snmpUDPPort}}`;
    this.ctx.body = {
      msg: result.msg,
      data: result.id,
    };
  }
  async delete() {
    /**
        * @summary 删除olt。
        * @description 删除olt。
        * @router get /oltdelete
        * @request query string id
        */
    const id = this.ctx.query;
    const result = await this.ctx.model.Olt.findOne({ _id: id.id });
    await this.ctx.service.olt.delete(id);
    global.log.desc = `${result.name} ${result.oltIP} delete`;
    this.ctx.body = {
      msg: 'delete olt successful',
      status: 16,
    };
  }
  // 第一步 获取olt通不通
  async getOltStatus() {
    /**
    * @summary 获取oltStatus
    * @description 获取oltStatus
    * @router get /getoltstatus
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.getOltStatus(params);
    this.ctx.body = {
      msg: result.msg,
      flag: result.flag,
    };
  }
  // 第二步 通过SNMP获取systemName
  async getSystemName() {
    /**
    * @summary snmp获取systemName
    * @description snmp获取systemName
    * @router get /getsystemname
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.getSystemName(params);
    this.ctx.body = {
      flag: result.flag,
      msg: result.msg,
    };
  }
  // 第三步 创建RZAdmin
  async createRZAdmin() {
    /**
    * @summary 创建RZAdmin
    * @description 创建RZAdmin
    * @router get /createrzadmin
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.createRZAdmin(params);
    this.ctx.body = {
      flag: result.flag,
      msg: result.msg,
    };
  }
  // 第四步 获取Version
  async getOltVersion() {
    /**
    * @summary 获取Version
    * @description 获取Version
    * @router get /getversion
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.getOltVersion(params);
    this.ctx.body = {
      flag: result.flag,
      msg: result.msg,
    };
  }
  // 第五步 获取cpu占用
  async getOltInformation() {
    /**
    * @summary 获取cpu占用
    * @description 获取cpu占用
    * @router get /getinformation
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.getOltInformation(params);
    this.ctx.body = {
      flag: result.flag,
      msg: result.msg,
    };
  }
  // 第六步 获取olt温度
  async getOltTemperature() {
    /**
    * @summary 获取olt温度
    * @description 获取olt温度
    * @router get /gettemperature
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.getOltTemperature(params);
    this.ctx.body = {
      msg: result.msg,
      flag: result.flag,
    };
  }
  // 第七步 获取cardInformation
  async getCardInformation() {
    /**
    * @summary 获取cardinformation
    * @description 获取cardinformation
    * @router get /getcardinformation
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.getCardInformation(params);
    this.ctx.body = {
      flag: result.flag,
      msg: result.msg,
    };
  }
  // 第八步 获取PonPorts和UplinkPorts
  async getPonPortsAndUplinkPorts() {
    /**
    * @summary 获取ponports和uplinkports
    * @description 获取ponports和uplinkports
    * @router get /getponportsanduplinkports
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.getPonPortsAndUplinkPorts(params);
    this.ctx.body = {
      flag: result.flag,
      msg: result.msg,
    };
  }
  // 第九步 获取onuprofile
  async getONUProfile() {
    /**
    * @summary 获取zte 的onu-type
    * @description 获取zte 的onu-type
    * @router get /getonuprofile
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.getOltONUProfile(params);
    this.ctx.body = {
      flag: result.flag,
      msg: result.msg,
    };
  }
  // 第十步 获取dbaprofile
  async getDBAProfile() {
    /**
    * @summary 获取dbaProfile
    * @description 获取dbaProfile
    * @router get /getdbaprofile
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.getOltDBAProfile(params);
    this.ctx.body = {
      msg: result.msg,
      flag: result.flag,
    };
  }
  // 华为 获取lineProfile
  async getLineProfile() {
    /**
    * @summary 获取lineProfile
    * @description 获取lineProfile
    * @router get /getlineprofile
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.getOltLineProfile(params);
    this.ctx.body = {
      msg: result.msg,
      flag: result.flag,
    };
  }
  async getRemoteProfile(){
    /**
    * @summary 获取remoteProfile
    * @description 获取remoteProfile
    * @router get /getremoteprofile
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.getOltRemoteprofile(params);
    this.ctx.body = {
      msg: result.msg,
      flag: result.flag,
    };
  }
  // 第十一步 获取oltVlan
  async getOltVlan() {
    /**
    * @summary 获取vlan
    * @description 获取vlan
    * @router get /getoltvlan
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.getOltVlan(params);
    this.ctx.body = {
      msg: result.msg,
      flag: result.flag,
    };
  }
  //  获取oltMac地址
  async getOltMac() {
    /**
    * @summary 获取oltMac地址
    * @description 获取oltMac地址
    * @router get /getoltmac
    * @request query String OltId
    */
   const params = this.ctx.query
   const result = await this.ctx.service.olt.getOltMac(params);
   this.ctx.body = {
     msg:result.msg,
     flag:result.flag
   }
  }
  // 第十二步 获取speedProfile
  async getOltSpeedProfile() {
    /**
    * @summary 获取oltspeedprofile
    * @description 获取oltspeedprofile
    * @router get /getoltspeedprofile
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.getOltSpeedProfile(params);
    this.ctx.body = {
      msg: result.msg,
      flag: result.flag,
    };
  }
  // 第十三步 给olt创建Acsvlan
  async setOltAcsVlan() {
    /**
    * @summary 给olt创建tr069vlan
    * @description 给olt创建tr069vlan
    * @router get /setoltacsvlan
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.service.olt.setOltAcsVlan(params);
    this.ctx.body = {
      msg: result.msg,
      flag: result.flag,
    };
  }
  // 第十四步 获取olt上已注册的onu列表
  async getRegisteredONUList() {
    /**
    * @summary 获取olt上已注册的onu列表
    * @description 获取olt上已注册的onu列表
    * @router get /getregisteredonulist
    * @request query String OltId
    */
    const params = this.ctx.query;
    const { id: tid } = getCookieValue(this.ctx.cookies, 'token', 'tenant');
    params.tid = tid;
    const result = await this.ctx.service.olt.getRegisteredONUList(params);
    this.ctx.body = {
      msg: result.msg,
      flag: result.flag,
    };
  }
  // 第十五步 获取olt上未注册的onu列表
  async getUnregisteredONUList() {
    /**
    * @summary 获取olt上未注册的onu列表
    * @description 获取olt上未注册的onu列表
    * @router get /getunregisteredonulist
    * @request query String OltId
    */
    const params = this.ctx.query;
    const { id: tid } = getCookieValue(this.ctx.cookies, 'token', 'tenant');
    params.tid = tid;
    const result = await this.ctx.service.olt.getUnregisteredONUList(params);
    this.ctx.body = {
      msg: result.msg,
      flag: result.flag,
    };
  }
  // 第十六步 给onu上已注册的onu下发acs地址
  async setRegisteredOnuAcsUrl() {
    /**
    * @summary 给olt上已注册的onu下发acs地址
    * @description 给olt上已注册的onu下发acs地址
    * @router get /setregisteredonuacsurl
    * @request query String OltId
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.olt.setRegisteredOnuAcsUrl(params);
    this.ctx.body = {
      msg: result.msg,
      flag: result.flag,
    };
  }
}
module.exports = OltController;
